package com.fishbone.sso.handler;

import com.fishbone.common.utils.FastJsonUtil;
import com.fishbone.common.utils.WebUtil;
import com.fishbone.core.api.ResponseEntity;
import com.fishbone.core.api.ResultCode;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义Token验证失败处理器
 * @ClassName CustomAuthenticationEntryPoint
 * @Author huyaxi
 * @DATE 2020/3/5 16:23
 */
@Slf4j
public class FishBoneAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @SneakyThrows
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        if (authException instanceof OAuth2AuthenticationException) {
            WebUtil.response(response,FastJsonUtil.toJSONString(ResponseEntity.fail(ResultCode.UN_AUTHORIZED)));
        }
        if (authException instanceof AuthenticationCredentialsNotFoundException) {
            WebUtil.response(response,FastJsonUtil.toJSONString(ResponseEntity.fail(ResultCode.UN_AUTHORIZED)));
        }
    }
}
